/*
 * Copyright (c) 2022, IMMORTA Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * - Neither the name of IMMORTA Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*!
 * @file timer_drv.c
 * @brief This file defines timer driver functions
 */

/*******Includes***************************************************************/
#include <stddef.h>
#include "timer_reg_access.h"

/*******Definitions************************************************************/

/*******Variables**************************************************************/
/*! @brief Table to save register base addresses for timer instances */
static TIMER_Type* s_timerRegBase[CONFIG_TIMER_INSTANCE_COUNT] = CONFIG_TIMER_REG_BASE_PTRS;

/*! @brief Table to save clock names for timer instances */
static clk_names_t s_timerClkName[CONFIG_TIMER_INSTANCE_COUNT] = CONFIG_TIMER_CLOCK_NAMES;

/*! @brief Table to save module names for timer instances */
static module_names_t s_timerModuleName[CONFIG_TIMER_INSTANCE_COUNT] = CONFIG_TIMER_MODULE_NAMES;

/*! @brief Table to save function source clock for timer instances */
static timer_clk_src_t s_timerSrcClk[CONFIG_TIMER_INSTANCE_COUNT] = CONFIG_TIMER_DEFAULT_SRCCLK;

/*******Prototypes*************************************************************/

/*******Private Functions******************************************************/
/*******************************************************************************
 *** Function Name : TIMER_UsToCount
 *** Description   : Convert compareValueByUs to compareValueByCount
 ******************************************************************************/
static uint32_t TIMER_UsToCount(uint32_t freq,
                                uint8_t prescaler,
                                uint32_t compareValueByUs)
{
    ASSERT_PARAM(freq > 0U);

    uint64_t ticksWithoutPrescaler = (uint64_t)compareValueByUs * (uint64_t)freq;
    uint64_t compareValueByCount;

    ticksWithoutPrescaler = (ticksWithoutPrescaler + 500000U) / 1000000U;
    compareValueByCount = (ticksWithoutPrescaler + (((uint64_t)prescaler + 1U) >> 1U)) / ((uint64_t)prescaler + 1U);
    compareValueByCount = (compareValueByCount < 1U) ? 1U : compareValueByCount;
    compareValueByCount = compareValueByCount - 1U;
    compareValueByCount = (compareValueByCount > 0xFFFFFFFFU) ? 0xFFFFFFFFU : compareValueByCount;

    return (uint32_t)compareValueByCount;
}

/*******************************************************************************
 *** Function Name : TIMER_CountToUs
 *** Description   : Convert compareValueByCount to compareValueByUs
 ******************************************************************************/
static uint32_t TIMER_CountToUs(uint32_t freq,
                                uint8_t prescaler,
                                uint32_t compareValueByCount)
{
    ASSERT_PARAM(freq > 0U);

    uint64_t ticksWithoutPrescaler = ((uint64_t)compareValueByCount + 1U) * ((uint64_t)prescaler + 1U);
    uint64_t compareValueByUs = ((ticksWithoutPrescaler * 1000000U) + ((uint64_t)freq >> 1U)) / (uint64_t)freq;

    compareValueByUs = (compareValueByUs > 0xFFFFFFFFU) ? 0xFFFFFFFFU : compareValueByUs;

    return (uint32_t)compareValueByUs;
}

/*******Code*******************************************************************/

/*******************************************************************************
 *** Function Name : TIMER_Init
 *** Description   : Initial a timer instance
 ******************************************************************************/
void TIMER_Init(uint32_t instance, const timer_config_t* config, bool startCounter)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);
    ASSERT_PARAM(config != NULL);

    TIMER_Type* regBase = s_timerRegBase[instance];
    module_names_t timerModuleName = s_timerModuleName[instance];

    /* Set timer bus clock enable */
    CLOCK_SetModuleBusClockEnable(timerModuleName, true);
    /* Set timer instance in-active */
    CLOCK_SetModuleSoftResetState(timerModuleName, RESET_INACTIVE);

    TIMER_SetConfig(instance, config);

    if (startCounter) {
        TIMER_REG_SetEnable(regBase, true);
    }
}

/*******************************************************************************
 *** Function Name : TIMER_SetConfig
 *** Description   : Configure a timer instance
 ******************************************************************************/
void TIMER_SetConfig(uint32_t instance, const timer_config_t* config)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);
    ASSERT_PARAM(config != NULL);

    TIMER_Type* regBase = s_timerRegBase[instance];
    clk_names_t timerClkName = s_timerClkName[instance];
    uint32_t freq = 0U;
    uint32_t compareValueByCount = 0U;

    /* Configure clock source of timer instance */
    s_timerSrcClk[instance] = config->srcClk;
    /* Select timer function clock source */
    (void)CLOCK_SelectModuleClockSource(timerClkName, (uint16_t)(config->srcClk));

    TIMER_REG_SetIntEnable(regBase, config->intEnable);
    TIMER_REG_SetPrescaler(regBase, config->prescaler);

    if (config->counterUnits == TIMER_COUNTER_UNITS_TICKS) {
        compareValueByCount = config->compareValue;
    } else {
        (void)CLOCK_GetFreq(timerClkName, &freq);
        compareValueByCount = TIMER_UsToCount(freq, config->prescaler, config->compareValue);
    }
    TIMER_REG_SetCompareValue(regBase, compareValueByCount);
}

/*******************************************************************************
 *** Function Name : TIMER_GetConfig
 *** Description   : Get configuration of a timer instance
 ******************************************************************************/
void TIMER_GetConfig(uint32_t instance, timer_config_t* config)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);
    ASSERT_PARAM(config != NULL);

    TIMER_Type* regBase = s_timerRegBase[instance];

    config->srcClk = s_timerSrcClk[instance];
    config->intEnable = TIMER_REG_IsIntEnabled(regBase);
    config->prescaler = TIMER_REG_GetPrescaler(regBase);
    config->compareValue = TIMER_REG_GetCompareValue(regBase);
}

/*******************************************************************************
 *** Function Name : TIMER_Deinit
 *** Description   : De-initialize a timer instance
 ******************************************************************************/
void TIMER_Deinit(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    clk_names_t timerClkName = s_timerClkName[instance];
    module_names_t timerModuleName = s_timerModuleName[instance];

    /* Set timer instance active */
    CLOCK_SetModuleSoftResetState(timerModuleName, RESET_ACTIVE);
    /* Set timer bus clock disable */
    CLOCK_SetModuleBusClockEnable(timerModuleName, false);

    /* Configure clock source of timer instance as OFF */
    s_timerSrcClk[instance] = TIMER_CLK_SRC_OFF;
    (void)CLOCK_SelectModuleClockSource(timerClkName, (uint16_t)TIMER_CLK_SRC_OFF);
}

/*******************************************************************************
 *** Function Name : TIMER_SetCompareValueByCount
 *** Description   : Set the compare value in counter tick units for a timer
 ***                 instance
 ******************************************************************************/
errcode_t TIMER_SetCompareValueByCount(uint32_t instance, uint32_t compareValueByCount)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    errcode_t errCode = ERR_SUCCESS;
    TIMER_Type* regBase = s_timerRegBase[instance];
    bool timerIsEnabled = false;

    timerIsEnabled = TIMER_REG_IsEnabled(regBase);
    if (timerIsEnabled) {
        errCode = ERR_ERROR;
    } else {
        /* The compare value can only be set if the counter is disabled */
        TIMER_REG_SetCompareValue(regBase, compareValueByCount);
    }

    return errCode;
}

/*******************************************************************************
 *** Function Name : TIMER_GetCompareValueByCount
 *** Description   : Get current compare value in counter ticks
 ******************************************************************************/
void TIMER_GetCompareValueByCount(uint32_t instance, uint32_t* compareValueByCount)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);
    ASSERT_PARAM(compareValueByCount != NULL);

    TIMER_Type* regBase = s_timerRegBase[instance];

    *compareValueByCount = TIMER_REG_GetCompareValue(regBase);
}

/*******************************************************************************
 *** Function Name : TIMER_SetCompareValueByUs
 *** Description   : Set the compare value in micro seconds for a timer instance
 ******************************************************************************/
errcode_t TIMER_SetCompareValueByUs(uint32_t instance, uint32_t compareValueByUs)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    errcode_t errCode = ERR_SUCCESS;
    TIMER_Type* regBase = s_timerRegBase[instance];
    clk_names_t timerClkName = s_timerClkName[instance];
    bool timerIsEnabled = false;
    uint32_t freq = 0U;
    uint8_t prescaler = 0U;
    uint32_t compareValueByCount = 0U;

    timerIsEnabled = TIMER_REG_IsEnabled(regBase);
    if (timerIsEnabled) {
        errCode = ERR_ERROR;
    } else {
        /* The compare value can only be set if the counter is disabled */
        (void)CLOCK_GetFreq(timerClkName, &freq);
        prescaler = TIMER_REG_GetPrescaler(regBase);
        compareValueByCount = TIMER_UsToCount(freq, prescaler, compareValueByUs);

        TIMER_REG_SetCompareValue(regBase, compareValueByCount);
    }

    return errCode;
}

/*******************************************************************************
 *** Function Name : TIMER_GetCompareValueByUs
 *** Description   : Get current compare value in micro seconds
 ******************************************************************************/
void TIMER_GetCompareValueByUs(uint32_t instance, uint32_t* compareValueByUs)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);
    ASSERT_PARAM(compareValueByUs != NULL);

    TIMER_Type* regBase = s_timerRegBase[instance];
    clk_names_t timerClkName = s_timerClkName[instance];
    uint32_t freq = 0U;
    uint8_t prescaler = 0U;
    uint32_t compareValueByCount = 0U;

    (void)CLOCK_GetFreq(timerClkName, &freq);
    prescaler = TIMER_REG_GetPrescaler(regBase);
    compareValueByCount = TIMER_REG_GetCompareValue(regBase);

    *compareValueByUs = TIMER_CountToUs(freq, prescaler, compareValueByCount);
}

/*******************************************************************************
 *** Function Name : TIMER_GetComapreFlag
 *** Description   : Get compare flag status
 ******************************************************************************/
bool TIMER_GetCompareFlag(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    return TIMER_REG_GetCompareFlag(regBase);
}

/*******************************************************************************
 *** Function Name : TIMER_ClearCompareFlag
 *** Description   : Clear compare flag status
 ******************************************************************************/
void TIMER_ClearCompareFlag(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    TIMER_REG_ClearCompareFlag(regBase);
}

/*******************************************************************************
 *** Function Name : TIMER_IsRunning
 *** Description   : Check timer counter status
 ******************************************************************************/
bool TIMER_IsRunning(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    return TIMER_REG_IsEnabled(regBase);
}

/*******************************************************************************
 *** Function Name : TIMER_SetIntEnable
 *** Description   : Enable or disable timer interrput
 ******************************************************************************/
void TIMER_SetIntEnable(uint32_t instance, bool enable)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    TIMER_REG_SetIntEnable(regBase, enable);
}

/*******************************************************************************
 *** Function Name : TIMER_GetCounterValueByCount
 *** Description   : Get current timer counter value
 ******************************************************************************/
uint32_t TIMER_GetCounterValueByCount(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    return TIMER_REG_GetCounterValue(regBase);
}

/*******************************************************************************
 *** Function Name : TIMER_StartCounter
 *** Description   : Start timer counter
 ******************************************************************************/
void TIMER_StartCounter(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    TIMER_REG_SetEnable(regBase, true);
}

/*******************************************************************************
 *** Function Name : TIMER_StopCounter
 *** Description   : Stop timer counter
 ******************************************************************************/
void TIMER_StopCounter(uint32_t instance)
{
    ASSERT_PARAM(instance < CONFIG_TIMER_INSTANCE_COUNT);

    TIMER_Type* regBase = s_timerRegBase[instance];

    TIMER_REG_SetEnable(regBase, false);
}

/*******EOF********************************************************************/

